<?php
class ImageUploadComponent extends Object {
function uploadCrop(&$file, $dir) {
	$return = false;
	//current time in miliseconds
	$time = microtime ( 1 ) * 1000;
	$file['name']=md5($time).$file['name'];
	if(move_uploaded_file($file['tmp_name'],$dir.$file['name']))
	{
		//FINDS SIZE OF THE OLD FILE
		list($width, $height) = getimagesize($dir.$file['name']);
		/**
         * Thumbnail
         */
        //$path = $_SERVER['DOCUMENT_ROOT'] . '/files/images/';
        $this->makeimage($file['name'], 'thumb_', $dir, 100, 100*$height/$width);
        unlink($dir . $file['name']);
        $return = true;
	}
	return $return;
}
function upload(&$file, $dir) {
	$return = false;
	//current time in miliseconds
	$time = microtime ( 1 ) * 1000;
	$file['name']=md5($time).$file['name'];
	if(move_uploaded_file($file['tmp_name'],$dir.$file['name']))
	{
        $return = true;
	}
	return $return;
}
function makeimage($filename, $newfilename, $path, $newwidth, $newheight) {

	//SEARCHES IMAGE NAME STRING TO SELECT EXTENSION (EVERYTHING AFTER . )
	$image_type = strstr($filename, '.');

	//SWITCHES THE IMAGE CREATE FUNCTION BASED ON FILE EXTENSION
	switch ($image_type) {
		case '.jpg':
			$source = imagecreatefromjpeg($path . $filename);
			break;
		case '.jpeg':
			$source = imagecreatefromjpeg($path . $filename);
			break;
		case '.png':
			$source = imagecreatefrompng($path . $filename);
			break;
		case '.gif':
			$source = imagecreatefromgif($path . $filename);
			break;
		 case '.bmp':
			$source = imagecreatefromwbmp($path . $filename);
			break;
		case '.JPG':
			$source = imagecreatefromjpeg($path . $filename);
			break;
		case '.JPEG':
			$source = imagecreatefromjpeg($path . $filename);
			break;
		case '.PNG':
			$source = imagecreatefrompng($path . $filename);
			break;
		case '.GIF':
			$source = imagecreatefromgif($path . $filename);
			break;
		case '.BMP':
			$source = imagecreatefromwbmp($path . $filename);
			break;
		default:
			echo("Vui lòng chọn file hình ảnh hợp lệ (jpg, jpeg, png, gif, bmp)");
			die;
			break;
	}

	//CREATES THE NAME OF THE SAVED FILE
	$file = $newfilename . $filename;

	//CREATES THE PATH TO THE SAVED FILE
	$fullpath = $path . $file;

	//FINDS SIZE OF THE OLD FILE
	list($width, $height) = getimagesize($path . $filename);

	//CREATES IMAGE WITH NEW SIZES
	$thumb = imagecreatetruecolor($newwidth, $newheight);

	//RESIZES OLD IMAGE TO NEW SIZES
	imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

	//SAVES IMAGE AND SETS QUALITY || NUMERICAL VALUE = QUALITY ON SCALE OF 1-100
	imagejpeg($thumb, $fullpath, 60);

	//CREATING FILENAME TO WRITE TO DATABSE
	$filepath = $fullpath;

	//RETURNS FULL FILEPATH OF IMAGE ENDS FUNCTION
	//return $filepath;
}
}
?>